package com.caszx.chargingpile.activity;


import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.app.base.adapter.BaseClickRecyclerAdapter;
import com.app.base.adapter.BaseHeadFootAdapter;
import com.app.base.app.BaseTopBarDelayActivity;
import com.app.utils.DividerGridItemDecoration;
import com.app.view.CircularProgress;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.holder.battery.BluetoothHolder;
import com.caszx.chargingpile.utils.DialogHelp;
import com.caszx.chargingpile.utils.SnackbarHelp;

import de.greenrobot.event.EventBus;


/**
 *查找电站蓝牙，不需要匹配
 * */
public class BluetoothActivity extends BaseTopBarDelayActivity {

    private CircularProgress check_bluetooth;
    private  TextView txt_bluetooth_status;

    private RecyclerView mRecyclerView;
    private BaseHeadFootAdapter<BluetoothDevice> mRecyclerAdapter;

    private BluetoothAdapter mBtAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);
        setCenterTitle("蓝牙设备");
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mReceiver, filter);
    }

    @Override
    protected void findView() {
        check_bluetooth = (CircularProgress) findViewById(R.id.check_bluetooth);
        txt_bluetooth_status = (TextView) findViewById(R.id.txt_bluetooth_status);
        initRecyclerView();
        initBluetooth();
        scanDevices();

    }


    private void initBluetooth(){

        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
//        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
//             DialogHelp.showDialogOnlyMesg(getResources().getString(R.string.error_bluetooth_not_supported),null);
//            changeDiscovery(false);
//            return;
//        }
        if(mBtAdapter==null){
           DialogHelp.showDialogOnlyMesg(this,getResources().getString(R.string.error_bluetooth_not_supported),null);
            changeDiscovery(false);
            return;
        }

    }

    private void scanDevices(){
        if(mBtAdapter!=null){
            mRecyclerAdapter.clear();
            if (mBtAdapter.isDiscovering()) {
                mBtAdapter.cancelDiscovery();
            }
            //直接打开蓝牙
            mBtAdapter.enable();
            mBtAdapter.startDiscovery();
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_bluetooth,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        scanDevices();
        return super.onOptionsItemSelected(item);
    }

    private void initRecyclerView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        LinearLayoutManager layoutManager = new LinearLayoutManager( this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setHasFixedSize(true);
        DividerGridItemDecoration decoration = new DividerGridItemDecoration(this);
        decoration.setDividerPadding(16, 16);
        mRecyclerView.addItemDecoration(decoration);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerAdapter = new BaseHeadFootAdapter<>(R.layout.item_bluetooth,BluetoothHolder.class);
        mRecyclerView.setAdapter(mRecyclerAdapter);

        mRecyclerAdapter.setOnItemClickListener(new BaseClickRecyclerAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if(mBtAdapter.isDiscovering())
                    mBtAdapter.cancelDiscovery();
                changeDiscovery(false);
                BluetoothDevice device =mRecyclerAdapter.getItems().get(position);

               SnackbarHelp.showSnackbarMsg(BluetoothActivity.this,device.getAddress());
            }
        });
    }


    private void changeDiscovery(boolean isDiscovery){
        if(isDiscovery){
            check_bluetooth.setVisibility(View.VISIBLE);
            txt_bluetooth_status.setText("查找设备...");
        }else{
            check_bluetooth.setVisibility(View.GONE);
            if(mRecyclerAdapter.getItems()!=null){
                int size = mRecyclerAdapter.getItems().size();
                txt_bluetooth_status.setText("找到"+size+"个设备");
            }else{
                txt_bluetooth_status.setText("找到0个设备");
            }


        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
            mBtAdapter.disable();
        }
        unregisterReceiver(mReceiver);

    }


    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){

                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
                switch(state) {
                    case BluetoothAdapter.STATE_TURNING_ON:

                        break;
                    case BluetoothAdapter.STATE_ON:
                        if(!mBtAdapter.isDiscovering()){
                            scanDevices();
                        }

                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:

                        break;
                    case BluetoothAdapter.STATE_OFF:

                        break;
                }

            } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                changeDiscovery(true);

            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mRecyclerAdapter.add(device);
                }

            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                changeDiscovery(false);
            }
        }
    };
}
